package top.infopub.mgr.cap.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.cap.FinPlanSubDto;
import top.infopub.dto.cap.FinancingPlanDto;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.cap.dao.ContractGuarantyDao;
import top.infopub.mgr.cap.dao.FinancingPlanDao;
import top.infopub.mgr.cap.domain.FinancingPlanDomain;
import top.infopub.mgr.cap.jsonvo.FinancingPlanJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.FinancingPlanService;
import top.infopub.mgr.cap.vo.FinancingPlanVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.model.cap.FinancingInstitution;
import top.infopub.model.cap.FinancingName;
import top.infopub.model.cap.FinancingPlan;
import top.infopub.model.cap.FinancingPlanSub;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import java.util.Date;
import java.util.List;

@Service
public class FinancingPlanServiceImpl  extends GenericServiceImpl<FinancingPlan, String> implements FinancingPlanService {


    @Autowired
    private FinancingPlanDao financingPlanDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private OAFlowService oaFlowService;

    @Autowired
    private ContractGuarantyDao contractGuarantyDao;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private CapProcessManageService capProcessManageService;

    @Override
    public GenericDao<FinancingPlan, String> getDao() {
        return financingPlanDao;
    }




    @Override
    public Page<FinancingPlanDomain> selectByDomainWhere(Page<FinancingPlanDomain> page, FinancingPlanVo financingPlanVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<FinancingPlanDomain>) financingPlanDao.selectByDomainWhere(financingPlanVo);
    }

    @Override
    public FinancingPlanJsonVo queryDetailById(String id) {
        FinancingPlanJsonVo jsonVo = new FinancingPlanJsonVo();
        String codes = codeGeneratorConfigService.generatorCode("cap_financing_plan");
        List<FinancingName> financingNames = financingPlanDao.queryListFinancingName();
        //如果id为空需要项目名称下拉框
        if(StringUtils.isEmpty(id)){
            /*融资基础信息（下拉框）*/
            FinancingPlanDto dto = new FinancingPlanDto();
            dto.setCodes(codes);
            jsonVo.setFinancingPlanDto(dto);
            jsonVo.setNames(financingNames);
        }else {
            //否则查出详情
            /*融资基础信息与金融机构信息*/
            FinancingPlan finPlan = financingPlanDao.selectByPrimaryKey(id);
            FinancingPlanDto dto = new FinancingPlanDto();
            BeanUtils.copyProperties(finPlan, dto);
            if (financingNames != null && financingNames.size() > 0) {
                for (FinancingName fn : financingNames) {
                    if (fn == null) continue;
                    if (StringUtils.equals(fn.getProCode(), dto.getProCode())) {
                        dto.setProName(fn.getProName());
                        break;
                    }
                }
            }
            //根据procode查询融资主体和融资负责人
            FinancingPlanDto dto1 = financingPlanDao.selectByProCode(dto.getProCode());
            dto.setSgCoopId(dto1.getSgCoopId());
            dto.setLeader(dto1.getLeader());
            jsonVo.setFinancingPlanDto(dto);
//            /*融资基础信息（下拉框）*/
//            jsonVo.setNames(financingNames);
            /*金融机构信息（下拉框）*/
            List<FinPlanSubDto> institutions = queryDetailFinOrgList(dto.getProCode());
            jsonVo.setInstitutions(institutions);
            /*附件信息表*/
            List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(dto.getProCode(), ProjectFileTypeEnum.FILE_TYPE53.getCode(), null);
            jsonVo.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        }
        return jsonVo;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo edit(FinancingPlanDto financingPlanDto, List<FinPlanSubDto> detailList, List<ProjectAttachment> attachmentList, Integer submitType, AuthorizationVO vo) {
        FinancingPlan financingPlan=new FinancingPlan();
        //该项目存在直接做更新
        FinancingPlan tmpFp = financingPlanDao.queryByProCode(financingPlanDto.getProCode());
        if (financingPlanDto.getId() == null && financingPlanDto.getProCode()!=null)
        {
            //保存前先去查询数据库有没有相同的proCode
            String flag =  financingPlanDao.selectByProCodeFlag(financingPlanDto.getProCode());
            if ("true".equals(flag))
            {
                //已经有重复是项目了
                return RspVo.getFailureResponse(0, "保存失败,该项目已存在");
            }
        }
        if (tmpFp != null) financingPlanDto.setId(tmpFp.getId());
        BeanUtils.copyProperties(financingPlanDto,financingPlan);
        //判断id存不存在，存在就修改
        if(StringUtils.isNotEmpty(financingPlanDto.getId())){
            //校验数据是否存在
            FinancingPlan tmpPi = financingPlanDao.selectByPrimaryKey(financingPlanDto.getId());
            if (tmpPi == null) return RspVo.getFailureResponse(400, "融资方案数据不存在");
            //判断审批状态
            if (StringUtils.isNotBlank(tmpPi.getProcessStatus())
                    && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpPi.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpPi.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            financingPlan.setId(tmpPi.getId());
            financingPlan.setUptBy(vo.getId());
            financingPlan.setUptTime(new Date());
            //更新主表信息
            financingPlanDao.updateByIdSelective(financingPlan);
        }else{
            //新增主表信息
            financingPlan.setCodes(StringUtils.isNotBlank(financingPlanDto.getCodes()) ? financingPlanDto.getCodes() : IdFactory.getUUIDUpper());
            financingPlan.setAddBy(vo.getId());
            financingPlan.setAddTime(new Date());
            financingPlan.setUptBy(vo.getId());
            financingPlan.setUptTime(new Date());
            financingPlanDao.insertSelective(financingPlan);
        }

        if (detailList != null && detailList.size() > 0) {
            FinancingPlanSub fps;
            for (FinPlanSubDto tmp : detailList) {
                if (tmp == null) continue;
                fps = new FinancingPlanSub();
                fps.setFinancingPlanDesc(tmp.getFinancingPlanDesc());
                fps.setSetupFinancialId(tmp.getSetupFinancialId());
                fps.setFinPlanId(financingPlan.getId());
                fps.setUptBy(vo.getId());
                fps.setUptTime(new Date());
                if (StringUtils.isBlank(tmp.getId())) {
                    fps.setAddBy(vo.getId());
                    fps.setAddTime(new Date());
                    financingPlanDao.insertFinPlanSub(fps);
                } else {
                    fps.setId(tmp.getId());
                    financingPlanDao.modifyFinPlanSub(fps);
                }
            }
        }

        //更新附件信息
        projectAttachmentDao.deleteByWhere(financingPlan.getProCode(), ProjectFileTypeEnum.FILE_TYPE53.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }
        if (submitType == 1) {
            if (org.apache.commons.lang.StringUtils.isNotBlank(financingPlan.getOaId())) {
                oaFlowService.finishOA(financingPlan.getOaId());
            }
            String detailJson= JSON.toJSONString(queryDetailById(financingPlan.getId()));
            capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE15, detailJson, financingPlan.getId(), financingPlan.getProCode(), vo);

        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public List<FinancingName> queryListFinancingName() {
        return financingPlanDao.queryListFinancingName();
    }

    @Override
    public List<FinancingInstitution> queryListInstitutions(String proCode) {
        return financingPlanDao.queryListInstitutions(proCode);
    }

    @Override
    public List<FinPlanSubDto> queryDetailFinOrgList(String proCode) {
        return financingPlanDao.queryDetailFinOrgList(proCode);
    }
}
